//
//  SKRegisterVController.m
//  SKaURobot
//
//  Created by cdong on 16/2/18.
//  Copyright © 2016年 cdong. All rights reserved.
//

#import "SKRegisterVController.h"
#import "SKRegisterView.h"
#import "SKRegisterNextVController.h"
#import "SKRetrieveCodeVController.h"
#import "AFHTTPSessionManager.h"
#import "SKFirstVController.h"

@interface SKRegisterVController ()<UITextFieldDelegate>

@property (nonatomic ,strong)SKRegisterView *registerView;
@property (nonatomic ,assign)NSInteger pwdShiftFlag;
@property(nonatomic,strong)NSTimer *timer;
@property(nonatomic,strong)NSString *urlStrChoice;

@end

@implementation SKRegisterVController

- (void)loadView{
    self.registerView = [[SKRegisterView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    self.view = self.registerView;
}

- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    NSUserDefaults *defaut = [NSUserDefaults standardUserDefaults];
    NSInteger codeNew = 0;
    codeNew = [defaut integerForKey:@"registerOrGetCode"];
    if (codeNew == 101) {
        self.registerView.navigationVL.text = @"注册";
    }else if (codeNew == 102){
        self.registerView.navigationVL.text = @"找回密码";
        if ([self.registerView.phoneTF respondsToSelector:@selector(setAttributedPlaceholder:)]) {
            UIColor *color = [RGBColorEncapsulation colorWithRGB:0xbab9ba alpha:1];
            UIFont *font = [UIFont systemFontOfSize:15];
            self.registerView.phoneTF.attributedPlaceholder = [[NSAttributedString alloc]initWithString:@"请输入手机号或邮箱" attributes:@{NSForegroundColorAttributeName:color,NSFontAttributeName:font}];
        }
    }else if (codeNew == 103){
        self.registerView.navigationVL.text = @"绑定手机号";
        [self.registerView.nextRegisterBtn setTitle:@"绑定" forState:UIControlStateNormal];
    }
    self.view.backgroundColor = [RGBColorEncapsulation colorWithRGB:0xf4f4f4 alpha:1];
    [self.registerView.backBtn addTarget:self action:@selector(backBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.registerView.nextRegisterBtn addTarget:self action:@selector(nextBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.registerView.getIdentifyCodeBtn addTarget:self action:@selector(getIdentifyCodeBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChanged) name:UITextFieldTextDidChangeNotification object:self.registerView.phoneTF];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChanged) name:UITextFieldTextDidChangeNotification object:self.registerView.identifyCodeTF];
    self.registerView.phoneTF.delegate = self;
    self.registerView.identifyCodeTF.delegate = self;
}

// 输入框文字判断
- (void)textFieldChanged{
    if (![self.registerView.phoneTF.text isEqualToString:@""] && ![self.registerView.identifyCodeTF.text isEqualToString:@""]) {
        self.registerView.nextRegisterBtn.userInteractionEnabled = YES;
        [self.registerView.nextRegisterBtn setTitleColor:[RGBColorEncapsulation colorWithRGB:0xffffff alpha:1] forState:UIControlStateNormal];
    }else{
        self.registerView.nextRegisterBtn.userInteractionEnabled = NO;
        [self.registerView.nextRegisterBtn setTitleColor:[RGBColorEncapsulation colorWithRGB:0xffffff alpha:.5] forState:UIControlStateNormal];
    }
}

static BOOL requestFlag = NO;
- (void)countDownRequestTimer
{
    static int freezeCount = 1;
    static int Count = 59;
    if (!requestFlag) {
        requestFlag = YES;
        freezeCount = 1;
        Count = 59;
    }else{
        Count = 60 - freezeCount;
    }
    if (Count >= 1) {
        [self.registerView.getIdentifyCodeBtn setTitle:[NSString stringWithFormat:@"%ds后重发",Count] forState:UIControlStateNormal];
        freezeCount ++;
    }else{
        [self.timer invalidate];
        self.timer = nil;
        [self.registerView.getIdentifyCodeBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
        [self.registerView.getIdentifyCodeBtn setBackgroundColor:[RGBColorEncapsulation colorWithRGB:0xcc222a alpha:1]];
        [self.registerView.getIdentifyCodeBtn setEnabled:YES];
    }
}

// 发送验证码
- (void)getIdentifyCodeBtnAction:(UIButton *)sender{
    requestFlag = NO;
    if ([self.registerView.phoneTF.text isEqualToString:@""]) {
        [self alertReminderMessage:@"手机号不能为空"];
        return;
    }
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSString* phoneRegex = @"((13[0-9])|14[7]|(15[^4,\\D])|17[6,7,8]|(18[0-9]))\\d{8}$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",emailRegex];
    NSPredicate* phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    BOOL isEmailMatch = [emailTest evaluateWithObject:self.registerView.phoneTF.text];
    BOOL isMatch = [phoneTest evaluateWithObject:self.registerView.phoneTF.text];
    if (!isMatch && !isEmailMatch) {
        [self alertReminderMessage:@"手机号或邮箱不正确，请重新输入"];
        return;
    }

    NSUserDefaults *defaut = [NSUserDefaults standardUserDefaults];
    NSInteger codeNew = 0;
    codeNew = [defaut integerForKey:@"registerOrGetCode"];
    if (codeNew == 101) { // 注册
        self.urlStrChoice =  [NSString stringWithFormat:@"http://api.au-smart.cn/index.php?act=getcode&op=register&mobile=%@",self.registerView.phoneTF.text];
    }else if (codeNew == 102){ // 找回密码
        if (isMatch) {
            [defaut setInteger:120 forKey:@"getCodeEmailOrMobile"];
            self.urlStrChoice =  [NSString stringWithFormat:@"http://api.au-smart.cn/index.php?act=getcode&op=findpw&mobile=%@",self.registerView.phoneTF.text];
        }else if (isEmailMatch){ // 用邮箱找回密码
            [defaut setInteger:121 forKey:@"getCodeEmailOrMobile"];
            self.urlStrChoice = [NSString stringWithFormat:@"http://api.au-smart.cn/index.php?act=getMailCode&op=findpw&mail=%@",self.registerView.phoneTF.text];
        }
    }else if (codeNew == 103){ // 老用户绑定
        self.urlStrChoice =  [NSString stringWithFormat:@"http://api.au-smart.cn/index.php?act=getcode&op=bindMobile&mobile=%@",self.registerView.phoneTF.text];
    }
    
    NSString *utf = [self.urlStrChoice stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:utf parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
        NSNumber *error = [responseObject objectForKey:@"error"];
        NSNumber *errorCode = [responseObject objectForKey:@"errorCode"];
        if (error.integerValue == 0) {

            [self.registerView.getIdentifyCodeBtn setEnabled:NO];
            [self.registerView.getIdentifyCodeBtn setBackgroundColor:[RGBColorEncapsulation colorWithRGB:0x777777 alpha:1]];
            self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countDownRequestTimer) userInfo:nil repeats:YES];
        }else{
            if (errorCode.integerValue == 1001) {
                [self alertReminderMessage:@"手机号已被注册"];
            }else if (errorCode.integerValue == 1016){
                [self alertReminderMessage:@"手机号未绑定"];
            }else if (errorCode.integerValue == 1002) {
                [self alertReminderMessage:@"手机验证码发送失败"];
            }else if(errorCode.integerValue == 1019){
                [self alertReminderMessage:@"手机号已经被绑定"];
            }else if(errorCode.integerValue == 1012){
                [self alertReminderMessage:@"邮箱格式错误"];
            }else if(errorCode.integerValue == 1013){
                [self alertReminderMessage:@"邮箱已被绑定"];
            }else if(errorCode.integerValue == 1014){
                [self alertReminderMessage:@"邮箱验证码发送失败"];
            }else if(errorCode.integerValue == 1032){
                [self alertReminderMessage:@"用户未绑定该邮箱"];
            }else if(errorCode.integerValue == 1029){
                [self alertReminderMessage:@"无效的用户名"];
            }else if(errorCode.integerValue == 1009){
                [self alertReminderMessage:@"注册失败"];
            }else if(errorCode.integerValue == 1004){
                [self alertReminderMessage:@"用户名已被注册"];
            }else{
                [self alertReminderMessage:@"验证码发送失败"];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

// 返回
- (void)backBtnAction:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

// 注册／绑定 下一步
- (void)nextBtn:(UIButton *)sender{
    
//        NSUserDefaults *defaut = [NSUserDefaults standardUserDefaults];
//        NSInteger codeNew = 0;
//        codeNew = [defaut integerForKey:@"registerOrGetCode"];
//                if (codeNew == 101) {
//                    SKRegisterNextVController *nextViewController = [[SKRegisterNextVController alloc]init];
//                    [self.navigationController pushViewController:nextViewController animated:YES];
//                }else if (codeNew == 102){
//                    SKRetrieveCodeVController *nextVController = [[SKRetrieveCodeVController alloc]init];
//                    [self.navigationController pushViewController:nextVController animated:YES];
//                }else if (codeNew == 103){
//                    SKFirstVController *firstVC = [[SKFirstVController alloc]init];
//                    [self.navigationController pushViewController:firstVC animated:YES];
//                }
    
    if ([self.registerView.phoneTF.text isEqualToString:@""]) {
        [self alertReminderMessage:@"手机号不能为空"];
        return;
    }
    
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSString* phoneRegex = @"((13[0-9])|14[7]|(15[^4,\\D])|17[6,7,8]|(18[0-9]))\\d{8}$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",emailRegex];
    NSPredicate* phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    BOOL isEmailMatch = [emailTest evaluateWithObject:self.registerView.phoneTF.text];
    BOOL isMatch = [phoneTest evaluateWithObject:self.registerView.phoneTF.text];
    if (!isMatch && !isEmailMatch) {
        [self alertReminderMessage:@"手机号或邮箱不正确，请重新输入"];
        return;
    }
    if ([self.registerView.identifyCodeTF.text isEqualToString:@""]) {
        [self alertReminderMessage:@"验证码不能为空"];
        return;
    }
    NSUserDefaults *defaut = [NSUserDefaults standardUserDefaults];
    if (isMatch) {
        [defaut setInteger:120 forKey:@"getCodeEmailOrMobile"];
    }else if (isEmailMatch){
        [defaut setInteger:121 forKey:@"getCodeEmailOrMobile"];
    }

    NSInteger codeNew = 0;
    codeNew = [defaut integerForKey:@"registerOrGetCode"];
    
    // @"http://api.au-smart.cn/index.php?act=checkcode&mobile=13588827231&mobileCode=063096"  self.urlStrChoice =  [NSString stringWithFormat:@"http://api.au-smart.cn/index.php?act=getcode&op=bindMobile&mobile=%@",self.registerView.phoneTF.text,uid];
    NSInteger emailOrMobil = [defaut integerForKey:@"getCodeEmailOrMobile"];
    NSString *urlStr = @"";
    if (emailOrMobil == 120) {
        urlStr =  [NSString stringWithFormat:@"http://api.au-smart.cn/index.php?act=checkcode&mobile=%@&mobileCode=%@",self.registerView.phoneTF.text,self.registerView.identifyCodeTF.text];
    }else if (emailOrMobil == 121){
        urlStr = [NSString stringWithFormat:@"http://api.au-smart.cn/index.php?act=checkMailCode&mail=%@&mailCode=%@",self.registerView.phoneTF.text,self.registerView.identifyCodeTF.text];
    }
    NSString *utf = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:utf parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        if (emailOrMobil == 120) {
            [defaults setObject:self.registerView.phoneTF.text forKey:@"mobile"];
        }else if (emailOrMobil == 121){
            [defaults setObject:self.registerView.phoneTF.text forKey:@"email"];
        }
        NSString *sesskey = [responseObject objectForKey:@"sesskey"];
        NSNumber *error = [responseObject objectForKey:@"error"];
        NSNumber *errorCodeAll = [responseObject objectForKey:@"errorCode"];
        if (error.integerValue == 0) {
            if (codeNew == 101) {
                SKRegisterNextVController *nextViewController = [[SKRegisterNextVController alloc]init];
                [self.navigationController pushViewController:nextViewController animated:YES];
            }else if (codeNew == 102){
                SKRetrieveCodeVController *nextVController = [[SKRetrieveCodeVController alloc]init];
                [self.navigationController pushViewController:nextVController animated:YES];
            }else if (codeNew == 103){ // 老用户未绑定手机号
                // http://api.au-smart.cn/index.php?act=bindMobile&mobile=%@&uid=%@
                NSUserDefaults *defaut = [NSUserDefaults standardUserDefaults];
                NSNumber *uid = [defaut objectForKey:@"uid"];
                NSString *sesskey = [defaut objectForKey:@"sesskey"];
                NSString *urlband = [NSString stringWithFormat:@"http://api.au-smart.cn/index.php?act=bindMobile&mobile=%@&uid=%@&sesskey=%@",self.registerView.phoneTF.text,uid,sesskey];
                NSLog(@"bandmobil %@",urlband);
                NSString *utf = [urlband stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
                [manager POST:utf parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
                    
                } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    NSLog(@"%@",responseObject);
                    NSNumber *error = [responseObject objectForKey:@"error"];
                    NSNumber *errorCode = [responseObject objectForKey:@"errorCode"];
                    if (error.integerValue == 0) {
                        SKFirstVController *firstVC = [[SKFirstVController alloc]init];
                        firstVC.updateUIFlag = YES;
                        [self.navigationController pushViewController:firstVC animated:YES];
                    }else{
                        if (errorCode.integerValue == 1020){
                            [self alertReminderMessage:@"用户信息不存在"];
                        }else if (errorCode.integerValue == 1021) {
                            [self alertReminderMessage:@"手机号不正确"];
                        }else if(errorCode.integerValue == 1019){
                            [self alertReminderMessage:@"手机号已经被绑定"];
                        }else if(errorCode.integerValue == 1009){
                            [self alertReminderMessage:@"注册失败"];
                        }else if(errorCodeAll.integerValue == 1035){
                            [self alertReminderMessage:@"用户未登录"];
                        }else{
                            [self alertReminderMessage:@"绑定失败"];
                        }
                    }
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    
                }];
            }
        }else{
            if (errorCodeAll.integerValue == 1003){
                [self alertReminderMessage:@"验证码不正确，请重新输入"];
            }else if (errorCodeAll.integerValue == 1030 || errorCodeAll.integerValue == 1031) {
                [self alertReminderMessage:@"验证码过期"];
            }else if(errorCodeAll.integerValue == 1015){
                [self alertReminderMessage:@"验证码不正确，请重新输入"];
            }else if(errorCodeAll.integerValue == 1035){
                [self alertReminderMessage:@"用户未登录"];
            }else{
                [self alertReminderMessage:@"验证失败"];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

// 点击return回收键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

// 点击空白回收键盘
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.registerView.phoneTF resignFirstResponder];
    [self.registerView.identifyCodeTF resignFirstResponder];
}

// 提示弹框
- (void)alertReminderMessage:(NSString *)message
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message message:@"" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:okAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)dissMissAction:(NSTimer *)timer
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [self.timer invalidate];
    self.timer = nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
